
package com.viewpagertext.fragments;


import static cn.jzvd.JZUtils.setRequestedOrientation;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.viewpagertext.Model.Video;
import com.viewpagertext.activitys.AllVideoActivity;
import com.viewpagertext.R;
import com.viewpagertext.activitys.PortAllActivity;
import com.viewpagertext.adapters.CustomVideoView;
import com.viewpagertext.utils.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Response;

/**
 *
 */
//private String videoApi="https://tenapi.cn/v2/wyymv?id=";
public class FriendFragment extends Fragment {
    public static List<Video> urls = new ArrayList<>();
    public static Video nowUrl;
    public static int nowCount=0,nowRandom=0;
    TextView auther,time,name;
    public static boolean flag=false;
    CustomVideoView videoview;
    Button start;
    Button next;
    Button prev;
    MediaController mediaController;
    public static  String videoApi="https://tenapi.cn/v2/wyymv?id=";
    private Spinner spinner_location;
    private ArrayAdapter arrayAdapter;
    //定义字符串数组,指定数组的元素
    private String[] spinner = new String[]{"默认MV","抖音短视频(即时)","快手短视频","随机短视频(即时)"};
    public static String type;

    Button all,fAll;
    private View view;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = inflater.inflate(R.layout.fragment_friend,container,false);
        videoview=view.findViewById(R.id.videoView);
        all=view.findViewById(R.id.all);
        fAll = view.findViewById(R.id.porall);
        mediaController= new MediaController(getContext());
        initview();
        //跳转全屏界面
        all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent backmain = new Intent(getActivity(), AllVideoActivity.class);
                startActivity(backmain);

                if (videoview != null && videoview.isPlaying()) {
                    System.out.println("不为空下一首");
                    videoview.pause();
                }

            }
        });
        fAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent backmain = new Intent(getActivity(), PortAllActivity.class);
                startActivity(backmain);

                if (videoview != null && videoview.isPlaying()) {
                    System.out.println("不为空下一首");
                    videoview.pause();
                }

            }
        });
        return view;
    }
    private  void initview(){

        start=view.findViewById(R.id.start);
        next=view.findViewById(R.id.next);
        prev=view.findViewById(R.id.prev);
        auther = view.findViewById(R.id.video_name);
        name = view.findViewById(R.id.video_text);
        time = view.findViewById(R.id.video_time);
        name.bringToFront();
        spinner_location=view.findViewById(R.id.spinner_location);

        //参数1.上下文对象 参数2.列表项的样式,Android为我们提供的资源样式为：android.R.layout.simple_spinner_item
        //参数3.定义的字符串数组
//        arrayAdapter=new ArrayAdapter(this, android.R.layout.simple_spinner_item,spinner);
        //设置适配器列表框下拉时的列表样式
        arrayAdapter=new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item,spinner);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将适配器与下拉列表框关联起来
        spinner_location.setAdapter(arrayAdapter);
        String s = spinner_location.getSelectedItem().toString();
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (nowCount==0) {
                    nextVideo();
                }else if(videoview.getDuration()!=0)
                {
                    if(!videoview.isPlaying())
                    {
                        videoview.start();
                        start.setBackgroundResource(R.mipmap.play);
                    }

                    else
                    {
                        videoview.pause();
                        start.setBackgroundResource(R.mipmap.pause);
                    }
                }
                else nextVideo();
            }
        });


        spinner_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = parent.getItemAtPosition(position).toString();
                System.out.println("下一首选择了"+result);
                //初始化
                urls.clear();
                nowUrl = null;
                nowCount = 0;

                type = result;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                prevVideo();
            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextVideo();
            }
        });
        videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // 当视频播放完成时，这里的代码会执行
                // 可以在这里添加您的逻辑，比如提示用户视频播放完毕，或者切换到下一个视频等
                start.setBackgroundResource(R.mipmap.pause);
            }
        });
        videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                // 当MediaPlayer准备完成并且开始播放时，这里的代码会执行
                // 可以在这里添加您的逻辑，比如记录日志、发送通知等
                start.setBackgroundResource(R.mipmap.play);
            }
        });
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // 这里处理触摸事件
                    if(!mediaController.isShowing())
                    mediaController.show();
                    else mediaController.hide();

                    // 如果你想拦截事件，返回true，否则返回false
                    return false;
                }
                return false;
            }
        });
        videoview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    // 处理触碰事件
                    if(!mediaController.isShowing())
                        mediaController.show();
                    else mediaController.hide();
                    // 如果你想拦截事件，返回true，否则返回false
                    return false;
                }
                return false;
            }
        });

    }

    public void nextVideo() {
        System.out.println("下一首"+nowCount+urls.size());
        if(type.equals("抖音短视频(即时)")&&nowCount >=urls.size()-1)
        {
            Video video = new Video();
            video.setAuther("未知");
            video.setUrl("http://api.yujn.cn/api/zzxjj.php?type=video");
            video.setTime("now");
            video.setName("抖音短视频");
            urls.add(video);
            nowUrl = video;
            nowCount++;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 在这里更新UI
                    // 例如，设置ImageView的可见性
                    init();
                }
            });
        }else if(type.equals("默认MV")&&nowCount >=urls.size()-1)
        {
            System.out.println("默认下一首"+flag);
            int randomNumber;
            if(flag ==false)
                {
                    Random random = new Random();
                    randomNumber = 5263043 + random.nextInt(600000); // 生成10到20之间的随机数

                }
            else {
                randomNumber = ++nowRandom;
            }
            System.out.println("下一首"+videoApi + randomNumber);
            HttpUtil.sendOkHttpRequest(videoApi + randomNumber, new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    flag = false;
                    nextVideo();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String videoDatas = response.body().string();

                    JSONObject jsonObject= null;
                    try {
                        jsonObject = new JSONObject(videoDatas);
                        int code = jsonObject.getInt("code");
                        System.out.println("获得代码"+code);
                        if(code ==200)
                        {
                            JSONObject data = jsonObject.getJSONObject("data");
                            // 从数据对象中获取信息
                            JSONObject mv = data.getJSONObject("mv");
                            String url = mv.getString("480");

                            Video video = new Video();
                            video.setAuther(data.getString("sings"));
                            video.setUrl(url);
                            video.setTime(data.getString("time"));
                            video.setName(data.getString("songs"));
                            urls.add(video);
                            nowUrl = video;
                            nowCount++;
                            flag = true;
                            nowRandom = randomNumber;
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // 在这里更新UI
                                    // 例如，设置ImageView的可见性
                                    init();
                                }
                            });
                        }
                        else {
                            flag = false;
                            nextVideo();
                        }
                    } catch (JSONException e) {
                        flag = false;
                        nextVideo();
                    }

                }
            });
        }
        else if(type.equals("随机短视频(即时)")&&nowCount >=urls.size()-1)
        {

            HttpUtil.sendOkHttpRequest("https://api.52vmy.cn/api/video/short", new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    nextVideo();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String videoDatas = response.body().string();

                    JSONObject jsonObject= null;
                    try {
                        jsonObject = new JSONObject(videoDatas);
                        int code = jsonObject.getInt("code");
                        System.out.println("获得代码"+code);
                        if(code ==200)
                        {
                            JSONObject data = jsonObject.getJSONObject("data");
                            // 从数据对象中获取信息
                            String url = data.getString("url");

                            Video video = new Video();
                            video.setAuther("随机作者");
                            video.setUrl(url);
                            video.setTime("未知时间");
                            video.setName(data.getString("title"));
                            urls.add(video);
                            nowUrl = video;
                            nowCount++;
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // 在这里更新UI
                                    // 例如，设置ImageView的可见性
                                    init();
                                }
                            });
                        }
                        else {
                            nextVideo();
                        }
                    } catch (JSONException e) {
                        nextVideo();
                    }

                }
            });
        }
        else if(type.equals("快手短视频")&&nowCount >=urls.size()-1)
        {
            System.out.println("下一首抖音短视频");
            nowCount++;
            HttpUtil.sendOkHttpRequest("https://api.yujn.cn/api/ks_sj.php?", new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    nextVideo();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String videoDatas = response.body().string();

                    JSONArray jsonObject= null;
                    try {
                        jsonObject = new JSONArray(videoDatas);
                        for(int i=0;i<jsonObject.length();i++)
                        {
                            JSONObject object = jsonObject.getJSONObject(i);
                            String title = object.getString("title");
                            String cover = object.getString("video");
                            String auther = "快手";
                            Video video = new Video();
                            video.setAuther(auther);
                            video.setUrl(cover);
                            video.setTime("未知时间");
                            video.setName(title);
                            urls.add(video);
                        }
                        nowUrl = urls.get(nowCount);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 在这里更新UI
                                // 例如，设置ImageView的可见性
                                init();
                            }
                        });
                    } catch (JSONException e) {
                        nextVideo();
                    }


                }
            });
        }
        else {
            nowUrl = urls.get(nowCount+1);
            nowCount++;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 在这里更新UI
                    // 例如，设置ImageView的可见性
                    init();
                }
            });
        }

    }

    private void prevVideo() {
        if(nowCount!=0)
        {
            nowUrl = urls.get(nowCount-1);
            nowCount--;
            init();
        }
    }

    private void init(){
        //启动视频播放的方法
//        String uri="http://vodkgeyttp8.vod.126.net/cloudmusic/mv/20180318025651/ad5f319e-551e-4625-8ad1-904802c7dbd0/3ae4edee6fbc6c4d6c2ea59625130804.mp4?wsSecret=43615beacc0c823afa47613f51c799db&wsTime=1717692326";
        System.out.println("下一首"+nowUrl.getAuther()+nowUrl.getTime()+nowUrl.getName());
        videoview.setVideoURI(Uri.parse(nowUrl.getUrl()));
        auther.setText(nowUrl.getTime());
        name.setText(nowUrl.getName());
        time.setText(nowUrl.getAuther());
        videoview.setMediaController(mediaController);
        mediaController.setMediaPlayer(videoview);
        videoview.requestFocus();//设置视频控制组件传入videoview对象
        videoview.start();//设置开始播放
    }
    @Override
    public void onPause() {
        super.onPause();
        // 当Activity暂停时停止视频播放
        if (videoview != null && videoview.isPlaying()) {
            videoview.stopPlayback();
        }
    }
}
